package com.dm.library.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 版    权:  深圳市迪蒙网络科技有限公司
 * 描    述:  <描述>
 * 修 改 人:  jiaohongyun
 * 修改时间:  2016/6/21
 */
public class PackageUtils {
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//        boolean isScreenOn = true;//如果为true，则表示屏幕“亮”了，否则屏幕“暗”了。
        if (Build.VERSION.SDK_INT < 20) {
            return pm.isScreenOn();
        } else {
            return pm.isInteractive();
        }
    }

    /**
     * 是否有sd卡
     *
     * @return
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 判断应用是否已经启动
     * @param context 一个context
     * @param packageName 要判断应用的包名
     * @return boolean
     */
    public static boolean isAppAlive(Context context, String packageName){
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

    /**
     * 判断是否后台运行
     *
     * @param context
     * @return
     */
    public static boolean isRunningPackName(Context context) {
        String packageName = context.getPackageName();
        return PackageUtils.getRunningPackName(context).equals(packageName);
    }

    public static String getRunningPackName(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        /** 获取当前正在运行的任务栈列表， 越是靠近当前运行的任务栈会被排在第一位，之后的以此类推 */
        List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1);

        /** 获得当前最顶端的任务栈，即前台任务栈 */
        ActivityManager.RunningTaskInfo runningTaskInfo = runningTasks.get(0);

        /** 获取前台任务栈的最顶端 Activity */
        ComponentName topActivity = runningTaskInfo.baseActivity;

        /** 获取应用的包名 */
        String packageName = topActivity.getPackageName();
        return packageName;
    }

    /**
     * 关闭软键盘
     */
    public static void closeKey(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 打开软键盘
     */
    public static void openKey(Context context, final EditText inputView) {
        final InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                inputMethodManager.showSoftInput(inputView, 0);
            }
        }, 300);
    }

    /**
     * 获取手机版本
     */
    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(Build.VERSION.SDK);
        } catch (NumberFormatException e) {

        }
        return version;
    }

    /**
     * 获取手机版本
     */
    public static String getPhoneVersion() {
        String version = null;
        try {
            version = Build.VERSION.RELEASE;
        } catch (NumberFormatException e) {

        }
        return version;
    }

    /**
     * 获取手机厂商
     */
    public static String getPhoneBrand() {
        String brand = null;
        try {
            brand = Build.BRAND;
        } catch (NumberFormatException e) {

        }
        return brand;
    }

    /**
     * 获取手机型号
     */
    public static String getPhoneModel() {
        String brand = null;
        try {
            brand = Build.MODEL;
        } catch (NumberFormatException e) {

        }
        return brand;
    }

    /**
     * 检测手机是否安装某个应用
     */
    public static boolean checkPackage(Context context, String packageName) {
        //获取手机中已安装的应用程序
        List<ApplicationInfo> mAppList = context.getPackageManager().getInstalledApplications(0);
        for (ApplicationInfo appInfo : mAppList) {
            if (appInfo.packageName.equals(TextUtils.isEmpty(packageName) ? "" : packageName)) {
                return true;
            }
        }
        return false;
    }

    /***
     * 根据包名杀死进程，然并卵
     *
     * @param context
     * @param packageName
     */
    public static void killOthreProgress(Context context, String packageName) {
        List<String> appNameList = getRunningProcess(context);
        if (null != appNameList && appNameList.size() > 0) {
            for (String appName : appNameList) {
                if (appName.equals(packageName)) {
                    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                    activityManager.killBackgroundProcesses(packageName);
                    //					activityManager.forceStopPackage(packageName);
                }
            }
        }
    }

    /***
     * 获取当前正在运行的进程
     *
     * @param context
     * @return
     */
    public static List<String> getRunningProcess(Context context) {
        List<String> mAppNameList = new ArrayList<String>(0);
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获取正在运行的应用
        List<ActivityManager.RunningAppProcessInfo> run = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo ra : run) {
            //这里主要是过滤系统的应用和电话应用，当然你也可以把它注释掉。
            if (ra.processName.equals("system") || ra.processName.equals("com.android.phone")) {
                continue;
            }
            mAppNameList.add(ra.processName);
        }
        return mAppNameList;
    }

    /**
     * 获取应用版本号
     *
     * @param context
     * @return
     */
    public static String getVersion(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    /**
     * 获取通知管理
     *
     * @param context
     * @return
     */
    public static NotificationManager getNotificationManager(Context context) {
        return (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

    }

    /***
     * 获取系统可用内存
     * @param context
     * @return
     */
    public static String getAvailMemory(Context context) {// 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }

    /***
     * 获取系统内存大小
     * @param context
     * @return
     */
    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

}
